package com.example.wemedia.controller;

import com.example.wemedia.service.WmMaterialService;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;

@RestController
@RequestMapping("wemedia/v1/")
@Api
@Slf4j
public class FileUploadController {
    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Value("${fastdfs.url}")
    private  String prefixUrl;
    

    /**
     * 上传图片submit
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload_file")
    public ResponseResult upload(MultipartFile file,String type) throws Exception {
        //byte[] imgBytes = file.getBytes();
        //ArrayList<byte[]> imageList = new ArrayList<>();
        //imageList.add(imgBytes);
        
        String imgUrl = fastDFSClient.uploadFile(file);
        Integer integer = wmMaterialService.saveMaterial(imgUrl, type);
        if (integer==1){
            return ResponseResult.okResult(prefixUrl+imgUrl);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

}
